package cn.HuanG.base.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("TOKEN");
        //不能获取-----没有拿到token【返回没有登录的提示  json】
        if(token!=null){
            Object o = redisTemplate.opsForValue().get(token);
//            可以获取------验证【token】数据
//            token不可用------redis中没有token【返回没有登录的数据  json】
            if (o!=null){
                //刷新过期时间
                redisTemplate.opsForValue().set(token,o,30, TimeUnit.MINUTES);
                return true;
            }
        }
        //设置响应类型为json
        response.setContentType("application/json;charset=UTF-8");
        //3.其他拦截的情况 返回错误的json 格式的提示
        PrintWriter writer = response.getWriter();
        //返回错误的json {"success":false,"message":"noAuth"}
        writer.println("{\"success\":false,\"message\":\"noAuth\"}");
        return false;
    }
}
